using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Infrastructure.CmsDbContext;
using JGSY.CMS.LowCode.Platform.Infrastructure.Extensions;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.ServiceModules.Modules
{
    /// <summary>
    /// 数据库服务模块
    /// 包含数据库上下文、仓储、延迟连接等数据访问服务
    /// </summary>
    public class DatabaseModule : IServiceModule
    {
        public string ModuleName => "数据库服务";
        public int Priority => 5;
        public bool LoadInFastMode => true; // 快速模式使用延迟连接
        public ModulePermission RequiredPermission => ModulePermission.DatabaseServices;
        public bool IsCriticalModule => true; // 关键模块

        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            // 完整数据库功能
            ConfigureDatabase(services, configuration);
            ConfigureRepositories(services);
        }

        public void ConfigureMinimalServices(IServiceCollection services, IConfiguration configuration)
        {
            // 精简数据库功能 - 使用延迟连接
            services.AddLowCodeDbContext(configuration);
            services.AddScoped<ILazyDbContextFactory<LowCodeDbContext>, LazyDbContextFactory<LowCodeDbContext>>();
            services.AddScoped<LowCodeDbContext>(serviceProvider =>
            {
                var factory = serviceProvider.GetRequiredService<ILazyDbContextFactory<LowCodeDbContext>>();
                return factory.CreateDbContext();
            });
            
            // 仅注册核心Repository
            services.AddCoreRepositories();
        }

        public bool ValidateConfiguration(IConfiguration configuration)
        {
            var connectionString = GetConnectionString(configuration);
            return !string.IsNullOrEmpty(connectionString);
        }

        private void ConfigureDatabase(IServiceCollection services, IConfiguration configuration)
        {
            // 数据库上下文注册
            services.AddLowCodeDbContext(configuration);
            
            // 在快速模式下，使用延迟数据库连接
            if (IsInFastMode(configuration))
            {
                services.AddScoped<ILazyDbContextFactory<LowCodeDbContext>, LazyDbContextFactory<LowCodeDbContext>>();
                services.AddScoped<LowCodeDbContext>(serviceProvider =>
                {
                    var factory = serviceProvider.GetRequiredService<ILazyDbContextFactory<LowCodeDbContext>>();
                    return factory.CreateDbContext();
                });
            }
        }

        private void ConfigureRepositories(IServiceCollection services)
        {
            // 注册所有Repository服务
            services.AddModularRepositories();
        }

        private bool IsInFastMode(IConfiguration configuration)
        {
            return JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.StartupOptimizations.IsFastStartupEnabled(configuration);
        }

        private string? GetConnectionString(IConfiguration configuration)
        {
            var mapper = new JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.AppSettingsMapper(configuration);
            var databaseConfig = mapper.Bind<JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.Models.DatabaseConfiguration>("");
            
            var dbType = databaseConfig.DatabaseType ?? "Postgres";
            return dbType.ToLower() switch
            {
                "mysql" => configuration.GetConnectionString("MySQL"),
                "sqlserver" => configuration.GetConnectionString("SqlServer"),
                "sqlite" => configuration.GetConnectionString("SQLite"),
                "postgres" => configuration.GetConnectionString("Postgres"),
                _ => configuration.GetConnectionString("DefaultConnection")
            };
        }
    }
}
